#!/bin/bash

# 操作
action="$1"
# 版本
version="$2"
# ip
remote_addr="$3"

serviceName="gmf-risk-platform-admin-lw"
image="$serviceName:$version"

# 打镜像
# build_image
npm_build(){
    rm -rf devops/dist
    #echo "【npm install】========================================="
    #npm install --registry=https://registry.npmmirror.com
    unzip -d devops/ devops/dist.zip
    rm -rf devops/dist.zip
    # echo "【npm run build】======================================="
    # npm run build:prod --unsafe-perm
    # if [ $? -ne 0 ]; then
    #     echo "npm run build 失败！==============================】"
    #     exit
    # fi
    # echo "【install build完成】===================================="
    # cp -r dist/ devops/
    
}
docker_build(){
    CID=$(docker ps -a | grep "$serviceName" | awk '{print $1}')
    echo "容器CID $CID"
    if [ -n "$CID" ]
    then
        echo "【容器存在 $serviceName:$CID】==============================="
        #停止
        echo "【停止容器 $serviceName:$CID】==============================="
        docker stop $CID
        #删除容器
        echo "【删除容器 $serviceName:$CID】==============================="
        docker rm $CID
    else
        echo "【容器不存在: $serviceName】================================="
    fi

    IID=$(docker images | grep "$serviceName" | awk '{print $3}')
    if [ -n "$IID" ]
    then
        echo "【镜像存在 $serviceName:$version:$IID】======================="
        docker rmi $IID
    else
        echo "【镜像不存在 $serviceName:$version】=========================="
    fi
    echo "【build_image $image】==================================="
    docker build -t $image devops/. 
}

# 部署
# deploy
deploy(){
    echo "【开始部署】 ======================================================"
    version="$version" IPADDR="$remote_addr" docker-compose -f devops/docker-compose.yml up -d 
    docker ps |grep $serviceName

}

main(){
    if [ "$action" = "npm_build" ];then
       npm_build
    fi
    if [ "$action" = "docker_build" ];then
       docker_build
    fi
    if [ "$action" = "deploy" ];then
       deploy
    fi
}

main






























